package com.sora.transport.socket.server;

import com.sora.handler.RequestHandler;
import com.sora.entity.RpcRequest;
import com.sora.entity.RpcResponse;
import com.sora.registry.ServiceRegistry;
import com.sora.serializer.CommonSerializer;
import com.sora.util.ObjectReader;
import com.sora.util.ObjectWriter;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

/**
 * @Classname: RequestHandlerThread
 * @Description:
 * @Author: Stonffe
 * @Date: 2023/4/30 17:35
 */
@AllArgsConstructor
public class SocketRequestHandlerThread  implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(SocketRequestHandlerThread.class);

    private Socket socket;
    private RequestHandler requestHandler;
    private CommonSerializer serializer;
    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            // 获取request对象
            RpcRequest request = (RpcRequest) ObjectReader.readObject(inputStream);
            String interfaceName = request.getInterfaceName();
            Object result = requestHandler.handle(request);
            RpcResponse<Object> responce = RpcResponse.success(request.getRequestId(),result);
            ObjectWriter.writeObject(outputStream, responce, serializer);
        } catch (IOException e) {
            logger.error("调用或发送时有错误发生：", e);
        }
    }
}
